/*
 * @lc app=leetcode.cn id=399 lang=javascript
 *
 * [399] 除法求值
 */

// @lc code=start
/**
 * @param {string[][]} equations
 * @param {number[]} values
 * @param {string[][]} queries
 * @return {number[]}
 */
var calcEquation = function (equations, values, queries) {
  const obj = {};
  equations.forEach(([dividend, divisor], index) => {
    if (obj[dividend] && obj[divisor]) {
      return;
    }
    if (obj[dividend]) {
      obj[divisor] = [1 / values[index], dividend];
    } else if (obj[divisor]) {
      obj[dividend] = [values[index], divisor];
    } else {
      obj[dividend] = [values[index], divisor];
      obj[divisor] = [1, divisor];
    }
  });
  console.log({ obj });
  let sign = true;
  while (sign) {
    sign = false;
    for (let key in obj) {
      const [rate, val] = obj[key];
      console.log({ key, val });
      if (Object.keys(obj).includes(val) && key !== val) {
        const [newRate, newVal] = obj[val];
        if (val === newVal) {
          continue;
        }
        sign = true;
        obj[key] = [rate * newRate, newVal];
      }
    }
  }
  console.log({ obj });
  return queries.map(([dividend, divisor]) => {
    if (!obj[dividend] || !obj[divisor]) {
      return -1;
    }
    if (obj[dividend][1] !== obj[divisor][1]) {
      return -1;
    }
    return obj[dividend][0] / obj[divisor][0];
  })
};

const res = calcEquation([["a", "b"], ["e", "f"], ["b", "e"]], [3.4, 1.4, 2.3], [["b", "a"], ["a", "f"], ["f", "f"], ["e", "e"], ["c", "c"], ["a", "c"], ["f", "e"]])
console.log(res);
// @lc code=end

// a = 3.4 * b;
// e = 1.4 * f;
// b = 2.3 * e;